﻿using UnityEngine;
using System.Collections;
using UnityExtension;

/// <summary>
/// unity MonoBehaviour单例模板
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonMono<T>:MonoBehaviour where T : SingletonMono<T>, new()
{
	protected static T s_Instance = null;
	/// <summary>
	/// 检测实例是否为null的标志
	/// 用于解决unity new Object() == null 为true的情况
	/// </summary>
	protected static bool instanceIsNull = true;
	/// <summary>
	/// 取得当前对象的一个单例
	/// </summary>
	public static T instance
	{
		get
		{
			if(instanceIsNull)
			{
				var ins = FindObjectOfType<T>();
				if(!ins)
				{
					var mainObj = GameObjectUtility.FindOrNew("Main");
					ins = mainObj.AddComponent<T>();
				}
				ins.AppyInstance();
			}
			return s_Instance;
		}
	}
	protected virtual void Awake()
	{
		AppyInstance();
	}
	protected void AppyInstance()
	{
		if(instanceIsNull)
		{
			s_Instance = this as T;
			instanceIsNull = false;
		}
	}
}
/// <summary>
/// C#单例模板
/// </summary>
/// <typeparam name="T"></typeparam>
public class SingletonObject<T> where T : class, new()
{
	protected static T _this = null;
	/// <summary>
	/// 取得当前对象的一个单例
	/// </summary>
	public static T Instance
	{
		get
		{
			if(_this == null)
			{
				_this = new T();
			}
			return _this;
		}
	}
}
